package com.am.server.config.websocket;


import cn.dev33.satoken.SaManager;
import cn.hutool.core.text.CharSequenceUtil;
import com.am.server.common.constant.Constant;
import org.jetbrains.annotations.NotNull;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.ErrorMessage;
import org.springframework.messaging.support.MessageHeaderAccessor;

/**
 * @author 阮雪峰
 */
public class WebSocketHandleInterceptor implements ChannelInterceptor {
    @Override
    public Message<?> preSend(@NotNull Message<?> message, @NotNull MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        assert accessor != null;
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            String token = accessor.getFirstNativeHeader(Constant.TOKEN);
            if (CharSequenceUtil.isBlank(token)) {
                return new ErrorMessage(new RuntimeException("非法用户"));
            }
            // 绑定user
            String stringUserId = SaManager.getSaTokenDao().get(String.format("%s:login:token:%s", SaManager.getConfig().getTokenName(), token));

            if (CharSequenceUtil.isBlank(stringUserId)) {
                return new ErrorMessage(new RuntimeException("非法用户"));
            }
        }
        return message;
    }
}
